<?PHP
session_start();
require_once("../../config/SysInitConfig.php");
//*********************************************************************************
$dir = $_SESSION['dir'];
if (empty($_SESSION['ModuleName']) || empty($dir)){
    die('SESSION已过期，请重新创建<a href="./index.php">返回</a>');
}
//DB类*****************************************************************************
if (is_file($dir . "/model/db/{$_SESSION['ModuleFileName']}ModelDB.php")) {
    $out .= $dir . "/model/db/{$_SESSION['ModuleFileName']}ModelDB.php DB类已存在，只能对字段信息进行更新...<br>";
    $rs = file_get_contents($dir . "/model/db/{$_SESSION['ModuleFileName']}ModelDB.php");
} else {
    $rs = file_get_contents("./module/TemplateModelDB.php");
    $rs = str_replace('{%ModuleName%}',$_SESSION['ModuleName'], $rs);
    $rs = str_replace('{%ModuleVarName%}',$_SESSION['ModuleVarName'], $rs);
    $rs = str_replace('{%ModuleFileName%}',$_SESSION['ModuleFileName'], $rs);
    $rs = str_replace('{%TableName%}',$_SESSION['TableName'], $rs);
}
$arr = explode("//field_arr start", $rs);
list($field_str, $ext) = explode("//field_arr end", $arr[1]);
$field_str = str_replace(array(" ", "\t", "\n", "\r"), "", $field_str);

$check_md5 = substr($ext, 1, 32);
if (md5($field_str) != $check_md5 && !empty($field_str)){
    $out .=  $dir . "/model/db/{$_SESSION['ModuleFileName']}ModelDB.php DB类字段配置已手动修改，自动生成配置写入不成功！<br>";
} else {
    $out .=  $dir . "/model/db/{$_SESSION['ModuleFileName']}ModelDB.php DB类字段配置信息已按设置更新！<br>";
    $field_arr = array();
    $primary_arr = array();
    foreach ($_POST['field'] as $k => $v) {
        preg_match("/([^\(]*)\((.*)\)/", $_POST['type_field'][$k], $match);
        $_POST['empty'][$k] = $_POST['empty'][$k] ? 0 : 1;
        $validate = $_POST['check'][$k] ? $_POST['empty'][$k] . '_' . $_POST['check'][$k] : $_POST['empty'][$k];
        $field_arr[$v] = array(
            'name' => $_POST['name'][$k],
            'type' => $match[1],
            'max_length' => $match[2],
            'validate' => $validate
        );
        if ($_POST['primary'][$k] == true) {
            $primary_arr[] = $v; 
        }
    }

    $str = var_export($field_arr, true);
    $str = "\nprotected \$field_arr = " . $str . ";\n    ";
    $str = str_replace("\n", "\n    ", $str);

    $rs = substr_replace($rs, $str, strpos($rs, "//field_arr start") + strlen("//field_arr start"), strpos($rs, "//field_arr end") - strpos($rs, "//field_arr start") - strlen("//field_arr start"));
    $md5 = md5(str_replace(array(" ", "\t", "\n", "\r"), "", $str));
    $rs = substr_replace($rs, " " . $md5, strpos($rs, "//field_arr end") + strlen("//field_arr end"), 32);
    $out .= $dir . "/model/db/{$_SESSION['ModuleFileName']}ModelDB.php DB类写入成功，内容如下：<br>";
    $out .= "<textarea name='null' rows='5' cols='100'>{$rs}</textarea><br>";
    file_put_contents($dir . "/model/db/{$_SESSION['ModuleFileName']}ModelDB.php", $rs);
}

//管理页面controller***********************************************************************************************
if (is_file($dir . "/app/{$_SESSION['app']}/controller/{$_SESSION['ModuleFileName']}Controller.php")) {
    $out .= $dir . "/app/{$_SESSION['app']}/controller/{$_SESSION['ModuleFileName']}Controller.php 控制器已存在，生成文件写入失败！<br>";
    $rs = file_get_contents($dir . "/app/{$_SESSION['app']}/controller/{$_SESSION['ModuleFileName']}Controller.php");
} else {
    $rs = file_get_contents("./module/TemplateController.php");
    $rs = str_replace('{%ModuleName%}',$_SESSION['ModuleName'], $rs);
    $rs = str_replace('{%ModuleVarName%}',$_SESSION['ModuleVarName'], $rs);
    $rs = str_replace('{%ModuleFileName%}',$_SESSION['ModuleFileName'], $rs);
    $rs = str_replace('{%TableName%}',$_SESSION['TableName'], $rs);
    $rs = str_replace('{%PageNum%}',$_SESSION['PageNum'], $rs);
    $rs = str_replace('{%Database%}',$_SESSION['db_mark'], $rs);
    $rs = str_replace('{%logicDelete%}',$_POST['logic_delete'], $rs);
    //更新条件
    $primaryWhereStr = '';//用于update/delete中查询数据
    $primaryWhere = '';
    $firstPrimaryField = '';//用于order排序
    $primaryStr = '';//用于日志主键
    foreach($primary_arr as $v) {
        $primaryWhereStr .= " AND `{$v}` = ?";
        $primaryWhere .= "        \$whereArr['$v'] = HttpParams::get('$v');\n";
        $firstPrimaryField = empty($firstPrimaryField) ? $v : $firstPrimaryField;
        $primaryStr .= " . '__' . HttpParams::get('{$v}')";
    }
    $primaryWhere = trim ($primaryWhere, " \n");
    $primaryWhereStr = trim ($primaryWhereStr, " AND ");
    $primaryStr = trim ($primaryStr, " . '_");
    $rs = str_replace('{%primaryWhereStr%}',$primaryWhereStr, $rs);
    $rs = str_replace('{%PrimaryWhere%}',$primaryWhere, $rs);
    $rs = str_replace('{%firstPrimaryField%}',$firstPrimaryField, $rs);
    $rs = str_replace('{%primaryStr%}',$primaryStr, $rs);
    //更新跳过主键
    $skipPrimay = "if (in_array(\$v, array('".implode("','", $primary_arr)."'))) {continue;}//跳过主键";
    $rs = str_replace('{%SkipPrimay%}',$skipPrimay, $rs);
    
    $createPk = $_SESSION['has_auto_increment'] ? "\${$_SESSION['ModuleVarName']}DB->insertId()" : $primaryStr;
    $rs = str_replace('{%createPk%}',$createPk, $rs);

    $out .= $dir . "/app/{$_SESSION['app']}/controller/{$_SESSION['ModuleFileName']}Controller.php 生成控制器写入文件成功，内容如下：<br>";
    $out .= "<textarea name='null' rows='5' cols='100'>{$rs}</textarea><br>";
    file_put_contents($dir . "/app/{$_SESSION['app']}/controller/{$_SESSION['ModuleFileName']}Controller.php", $rs);
}

//模版页面*********************************************************************************************************************
if (is_file($dir . "/app/{$_SESSION['app']}/templates/{$_SESSION['ModuleFileName']}.html")) {
    $out .= $dir . "/app/{$_SESSION['app']}/templates/{$_SESSION['ModuleFileName']}.html 模版已存在，生成文件写入失败！<br>";
    $rs = file_get_contents($dir . "/app/{$_SESSION['app']}/templates/{$_SESSION['ModuleFileName']}.html");
} else {
    $rs = file_get_contents("./module/Template.html");
    $rs = str_replace('{%ModuleName%}',$_SESSION['ModuleName'], $rs);
    $rs = str_replace('{%ModuleUrlName%}',$_SESSION['ModuleUrlName'], $rs);
    $rs = str_replace('{%ModuleVarName%}',$_SESSION['ModuleVarName'], $rs);
    $rs = str_replace('{%ModuleFileName%}',$_SESSION['ModuleFileName'], $rs);
    $rs = str_replace('{%TableName%}',$_SESSION['TableName'], $rs);
    $delete_a = empty($_POST['logic_delete']) ? 'delete' : "{=if \$item.{$_POST['logic_delete']} == 1=}logic_resume{=else=}logic_delete{=/if=}";
    $delete_word = empty($_POST['logic_delete']) ? '删除' : "{=if \$item.{$_POST['logic_delete']} == 1=}恢复{=else=}删除{=/if=}";
    $delete_status = empty($_POST['logic_delete']) ? "" : "{=if \$item.{$_POST['logic_delete']} == 1=} del{=/if=}";
    //主键操作url
    $primaryUrl = '';
    $primaryKey = '';
    foreach($primary_arr as $v) {
        $primaryUrl .= "&{$v}={=\$item.$v=}";
        $primaryKey .= "_{=\$item.$v=}";
    }
    //列表\FROM
    $theader = "<tr>\n";
    $tbody = '<tr class="{=cycle values=\',odd\'=}'.$delete_status.'" id="tr'.$primaryKey.'">';
    $tbody .= "\n";
    $form = '<div id="'.$_SESSION['ModuleUrlName'].'_update_dialog" style="display:none;" title="'.$_SESSION['ModuleName'].'编辑">';
    $form .= "\n";
    $form .= '<form class="form" action="" method="post">';
    $form .= "\n";
    $search = '';
    foreach($_POST['field'] as $k => $v) {
        if ($_POST['show_field'][$k] == true) {
            $theader .= "\t\t\t\t\t\t<th>{$_POST['name'][$k]}</th>\n";
            $tbody .= "\t\t\t\t\t\t<td class=\"td_{$v}\">{=\$item.{$v}=}</td>\n";
        }
        if ($_POST['add_field'][$k] == true) {
            $form .= '<div class="form_div"><div style="float:left;width:80px;">'.$_POST['name'][$k].'：</div><input type="text" name="'.$v.'" value="" /></div>';
            $form .= "\n";
        }
        if ($_POST['search_field'][$k] == true) {
            $search .= '<option value="'.$v.'">'.$_POST['name'][$k].'</option>';
        }
    }
    $theader .= "\t\t\t\t\t\t<th>操作</th></tr>";
    $theader .= "\n";
    $tbody .= "\t\t\t\t\t\t" . '<td>[<a href="javascript:void(0);" class="opt"  data-opt_id="'.$_SESSION['ModuleUrlName'].'_update_dialog" data-opt_type="dialog" data-opt_width="520" data-opt_url="' . URL_ROOT . '?'.STATE."={$_SESSION['ModuleUrlName']}&".ACTION.'=get'.$primaryUrl.'" data-opt_action="' . URL_ROOT . '?'.STATE."={$_SESSION['ModuleUrlName']}&".ACTION.'=update'.$primaryUrl.'" alt="'.$_SESSION['ModuleName'].'编辑" title="'.$_SESSION['ModuleName'].'编辑" >编辑</a>] | [<a href="javascript:void(0);" class="opt"  data-opt_id="'.$_SESSION['ModuleUrlName'].'_'.$delete_a.'" data-opt_url="' . URL_ROOT . '?'.STATE."={$_SESSION['ModuleUrlName']}&".ACTION.'='.$delete_a.$primaryUrl.'" alt="'.$_SESSION['ModuleName'].$delete_word.'" title="'.$_SESSION['ModuleName'].$delete_word.'" >'.$delete_word.'</a>]</td></tr>';
    $tbody .= "\n";
    $form .= '<div style="padding-top:10px;text-align:center;"><input type="submit" class="button" id="submit" value="提交"></div></form>';
    $rs = str_replace('{%theader%}',$theader, $rs);
    $rs = str_replace('{%tbody%}',$tbody, $rs);
    $rs = str_replace('{%Form%}',$form, $rs);
    $rs = str_replace('{%Search%}',$search, $rs);
    $rs = str_replace('{%CreateAction%}', URL_ROOT . '?'.STATE."={$_SESSION['ModuleUrlName']}&".ACTION.'=create', $rs);

    $out .= $dir . "/app/{$_SESSION['app']}/templates/{$_SESSION['ModuleFileName']}.html 生成模版写入成功，内容如下：<br>";
    $out .= "<textarea name='null' rows='5' cols='100'>{$rs}</textarea><br>";
    file_put_contents($dir . "/app/{$_SESSION['app']}/templates/{$_SESSION['ModuleFileName']}.html", $rs);
}

//生成菜单*********************************************************************************************************************

if (is_file($dir . "/app/{$_SESSION['app']}/templates/left.html")) {
    $rs = file_get_contents($dir . "/app/{$_SESSION['app']}/templates/left.html");
    if (!strpos($rs, URL_ROOT . "?".STATE."={$_SESSION['ModuleUrlName']}&".ACTION."=view")) {
            $rs = str_replace("{=*后台菜单*=}", "<h1 class=\"item1\">{$_SESSION['ModuleName']}管理</h1>\n<div class=\"block\">\n\t<ul>\n\t\t<li><a href=\"" . URL_ROOT . "?".STATE."={$_SESSION['ModuleUrlName']}&" . ACTION . "=view"."\">{$_SESSION['ModuleName']}列表</a></li>\n\t</ul>\n</div>\n{=*后台菜单*=}", $rs);
        file_put_contents($dir . "/app/{$_SESSION['app']}/templates/left.html", $rs);
        $out .= $dir . "/app/{$_SESSION['app']}/templates/left.html 生成左侧菜单成功。<br>";
    } else {
        $out .= $dir . "/app/{$_SESSION['app']}/templates/left.html 左侧菜单已存在，无改动。<br>";
    }
} else {
    $out .= $dir . "/app/{$_SESSION['app']}/templates/left.html 不存在，无法生成菜单。<br>";
}
$out .= '<div style="font-size:20px;padding-top:20px;">点击<a href="./../../index.php?s='.$_SESSION['ModuleVarName'].'&a=view" target="_blank" style="color:#f00;">这里</a>访问该后台管理模块<span style="font-size:12px;color:#f00;">(请确保/config/Configure.php中的app选择器选择为后台APP_ADMIN)</span></div>';
?>
<html>
<head>
<title>模板构架</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style>
body {text-align:center;padding-top:50px;background-color:#F7E8AC;}
table {font-size:12px; line-height:20px;border-color:#FF9900; border-style:groove}
th {background-color:#FF9900; font-size:14px; font-weight:bold;}
td {padding-left:5px; border-style:inherit; border:1px dashed #FF9900;}
textarea {font-size:12px;}
</style>
</head>
<body>
<table align=center border=1>
<tr><th>生成结果</th></tr>
<tr><td><?php echo $out;?></td></tr>
</table>
</body>
</html>